//
//  AppDelegate.m
//  OTOClient
//
//  Created by Suny on 15/3/13.
//  Copyright (c) 2015年 Suny. All rights reserved.
//

#import "IntroduceView.h"
#import "HomeViewController.h"
#import "LoginMenuViewController.h"
#import "SearchViewController.h"
#import "MyProfileViewController.h"
#import "TipAbstractListViewController.h"
#import "SlideTabInfo.h"
#import "AddViewController.h"
#ifdef TESTVERSION
#import "AFNetworkActivityLogger.h"
#endif

#import "LoginViewController.h"
#import "ContentViewController.h"

#import "TopicListViewController.h"
#import "SubTopicViewcontroller.h"
#import "UIBarButtonItem+BaseFramework.h"


#import <ShareSDK/ShareSDK.h>
#import "WeiboSDK.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"
@interface AppDelegate ()

@property (nonatomic,strong) NavigationController *loginNavigation;
@end

@implementation AppDelegate

DEF_SINGLETON();

- (void)addNotifications
{
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(netWorkStatusChangedNotification:)
												 name:kReachabilityChangedNotification
											   object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(didLoginSucceed:)
												 name:kLoginSucceedNotificationName
											   object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(didLoginOutSucceed:)
												 name:kLoginOutNotificationName
											   object:nil];
}


- (void)didLoginSucceed:(NSNotification *)notification
{	
	[self initMainView];

	_window.rootViewController = _rootNavigationController;
	
}

- (void)didLoginOutSucceed:(NSNotification *)notification
{
	if (!_loginNavigation) 
	{
		LoginViewController *loginVC = [LoginViewController sharedInstance];
        LoginMenuViewController *loginMenuViewController = [LoginMenuViewController sharedInstance];
        
		NavigationController *loginNavigation = [[NavigationController alloc] initWithRootViewController:loginMenuViewController];
        
		_loginNavigation = loginNavigation;
	}

	_window.rootViewController = _loginNavigation;
}

- (void)netWorkStatusChangedNotification:(NSNotification *)notification
{
	Reachability *info = [notification object];
	if (info)
	{
		NetworkStatus status = [info currentReachabilityStatus];
		switch (status) 
		{
			case NotReachable:
				DLog(@"当网络连接已经断开！");
				break;
			case ReachableViaWiFi:
				DLog(@"当前网络状态Wifi连接！");
				break;
			case ReachableViaWWAN:
				DLog(@"数据连接");
				break;
				
			default:
				break;
		}
	}
	
}


- (void)initShareSdk
{
    //1.初始化ShareSDK应用,字符串"4a88b2fb067c"换成你申请的ShareSDK应用的Appkey，这个key来源于ShareSDK官网上申请获得
    [ShareSDK registerApp:@"5ee6b38a8d02"];
    
    //2. 初始化社交平台
//    初始化新浪，在新浪微博开放平台上申请应用，这个方法会又客户端跳客户端，没客户端条web.
    [ShareSDK connectSinaWeiboWithAppKey:@"4047101423"
                               appSecret:@"a565c4e3dd3dbeaba8b95b14c54d6772"
                             redirectUri:@"https://www.baidu.com"
                             weiboSDKCls:[WeiboSDK class]];
    
    //初始化微信，微信开放平台上注册应用
    [ShareSDK connectWeChatWithAppId:@"wx4868b35061f87885"
                           appSecret:@"64020361b8ec4c99936c0e3999a9f249"
                           wechatCls:[WXApi class]];
    
    //连接QQ应用
    [ShareSDK connectQQWithQZoneAppKey:@"1104686460"
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    //连接QQ空间应用
    [ShareSDK connectQZoneWithAppKey:@"1104686460"
                           appSecret:@"eaQfRMoA1hlJc6AV"
                   qqApiInterfaceCls:[QQApiInterface class]
                     tencentOAuthCls:[TencentOAuth class]];
	
	[ShareSDK ssoEnabled:YES];
    
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	// Override point for customization after application launch.
    [self initShareSdk];

	[self addNotifications];
	[CoreManager sharedInstance];
	
	
	if ([application respondsToSelector:@selector(registerUserNotificationSettings:)])
	{
		UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
																							 |UIRemoteNotificationTypeSound
																							 |UIRemoteNotificationTypeAlert) categories:nil];
		[application registerUserNotificationSettings:settings];
	} 
	else 
	{
		UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
		[application registerForRemoteNotificationTypes:myTypes];
	}
	
	[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
	[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
	_window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	
	// Override point for customization after application launch.
	self.window.backgroundColor = [UIColor whiteColor];
	
	
	// 如果是第一次进来就加载引导页面
	if ([[CoreManager sharedInstance] appInfo].currentLoginNumber < kShowIntroduceViewLoginCount)
	{
		[IntroduceView showWithComplete:^(IntroduceView *introduceView){
			
			[self initMainView];
			[self didLoginOutSucceed:nil];
			[self.window makeKeyAndVisible];
			
		}];
	}
	else
	{
		[self didLoginOutSucceed:nil];
		[self.window makeKeyAndVisible];
	}
	
	
#ifdef TESTVERSION
	[[AFNetworkActivityLogger sharedLogger] startLogging];
	[[AFNetworkActivityLogger sharedLogger] setLevel:AFLoggerLevelDebug];
#endif
	return YES;
}

//添加两个回调方法,return的必须要ShareSDK的方法
- (BOOL)application:(UIApplication *)application
      handleOpenURL:(NSURL *)url
{
    return [ShareSDK handleOpenURL:url
                        wxDelegate:self];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [ShareSDK handleOpenURL:url
                 sourceApplication:sourceApplication
                        annotation:annotation
                        wxDelegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application {
	// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
	// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
	// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
	// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
	// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
	// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)initMainView
{
	_mainTabBarController = [[TabViewController alloc] init];
	
	_mainTabBarController.showBigItemCenter = YES;
	
	_mainTabBarController.customTabBar.backgroundColor = [UIColor grayColor];
	
	
	SlideTabInfo *slideTableInfo = [[SlideTabInfo alloc] init];
	slideTableInfo.tabTitle = @"热门";
	slideTableInfo.tabId = @"hot";	
	TipAbstractListViewController *hotListViewController = [[TipAbstractListViewController alloc] initWithSlideInfo:slideTableInfo];
	[self createTabBarItemForViewController:hotListViewController
							  selectedImage:@"hot_tips_selected"
								tabIconName:@"hot_tips"
								   tabTitle:@""];
    hotListViewController.hasNavigationBar = YES;

	
	SearchViewController *searchViewController = [[SearchViewController alloc] init];

    [self createTabBarItemForViewController:searchViewController
                              selectedImage:@"Newsearch_selected"
                                tabIconName:@"Newsearch"
                                   tabTitle:@""];


    AddViewController *addViewController = [[AddViewController alloc] init];

    [self createTabBarItemForViewController:addViewController
                              selectedImage:@"Newaddtip_selected"
                                tabIconName:@"Newaddtip"
                                   tabTitle:@""];



    slideTableInfo = [[SlideTabInfo alloc] init];
    slideTableInfo.tabTitle =  @"关注";
    slideTableInfo.tabId = @"interested";

    TipAbstractListViewController *interestedListViewController = [[TipAbstractListViewController alloc] initWithSlideInfo:slideTableInfo];


    [self createTabBarItemForViewController:interestedListViewController
							  selectedImage:@"Newpublictips_selected"
								tabIconName:@"Newpublictips"
								   tabTitle:@""];
    interestedListViewController.hasNavigationBar = YES;

    MyProfileViewController *profileViewController = [[MyProfileViewController alloc] init];
	
	profileViewController.userInfo = [LoginUserInfo sharedInstance];

    [self createTabBarItemForViewController:profileViewController
                              selectedImage:@"Newprofile_selected"
                                tabIconName:@"Newprofile"
                                   tabTitle:@""];

    _mainTabBarController.viewControllers = @[hotListViewController,searchViewController,addViewController,interestedListViewController,profileViewController];
	_rootNavigationController = [[NavigationController alloc] initWithNavigationBarClass:[NavigationBar class] toolbarClass:nil];
	_rootNavigationController.navigationBarHidden = YES;
	_mainTabBarController.delegate = self;
	
	

	_sideslipViewController = [SideslipViewController sharedSliderController];
	_sideslipViewController.MainVC = _mainTabBarController;
	
	[SideslipViewController sharedSliderController].LeftSContentOffset= 320 - 136;
//	[SideslipViewController sharedSliderController].LeftContentViewSContentOffset = 90;
	[SideslipViewController sharedSliderController].LeftSContentScale=0.77;
	[SideslipViewController sharedSliderController].LeftSJudgeOffset=160;
	
	[_rootNavigationController pushViewController:_sideslipViewController animated:NO];
	_sideslipViewController.canMoveWithGesture = NO;
	self.window.rootViewController =  _sideslipViewController;


}

- (BOOL)tabViewController:(TabViewController *)tabBarController willChangeToIndex:(NSInteger)index
{
	if (index == 2)
	{
		
		TopicListViewController *tpoicList = [[TopicListViewController alloc] init];
		
		
		SubTopicViewcontroller *subpicList = [[SubTopicViewcontroller alloc] init];
		
		SideslipViewController *sideslipViewController = [[SideslipViewController alloc] init];
		sideslipViewController.navigationItem.leftBarButtonItem = [UIBarButtonItem leftBarButtonItemWithImageName:@"navigationbar_back_icon"
																									   target:sideslipViewController
																									 selector:@selector(back)];
		sideslipViewController.hasNavigationBar = YES;
		[sideslipViewController setNavigationTitle: @"添加技巧"];
		sideslipViewController.MainVC = tpoicList;
		sideslipViewController.RightVC = subpicList;
		
		sideslipViewController.RightSContentOffset = 120;
		sideslipViewController.RightSContentScale = 1;
		sideslipViewController.mainBlackCoverMaxAlpha = 0;
		
		
		NavigationController *navigation = [[NavigationController alloc] init];
		[navigation pushViewController:sideslipViewController animated:NO];
		
		[_window.rootViewController presentViewController:navigation
						   animated:YES 
						 completion:nil];
		return NO;
	}
	
	return YES;
}

- (BaseViewController *)createTabBarItemForViewController:(BaseViewController*)viewController
											selectedImage:(NSString *)selectedImage
											  tabIconName:(NSString*)iconName
												 tabTitle:(NSString*)tabTitle
{
	if (viewController)
	{
		// 设置tabbar的image
		viewController.customTabBarItem.image = [UIImage imageNamed:iconName];
		viewController.customTabBarItem.highlightedImage = [UIImage imageNamed:selectedImage];
		viewController.customTabBarItem.selectedImage = [UIImage imageNamed:selectedImage];
		
		// 设置tabbar的title
		viewController.customTabBarItem.title = tabTitle;
		viewController.customTabBarItem.titleColor = [UIColor colorWithHex:0x555555];
		viewController.customTabBarItem.highlightedTitleColor = [UIColor colorWithHex:0xf84c4b];
		viewController.customTabBarItem.selectedTitleColor = [UIColor colorWithHex:0xf84c4b];
		
		viewController.hasNavigationBar = YES;
	}
	
	return viewController;
}


+ (NavigationController *)rootNavigationController
{
	return [(AppDelegate *)[[UIApplication sharedApplication] delegate] rootNavigationController];
}


+ (SideslipViewController *)sideslipViewController
{
    return [(AppDelegate *) [[UIApplication sharedApplication] delegate] sideslipViewController];
}
@end
